// 生成图片类型
const _fixType = (type) => {
	type = type.toLowerCase().replace(/jpg/i, 'jpeg');
	const r = type.match(/png|jpeg|bmp|gif/)[0];
	return 'image/' + r;
};
/**
 * 将base64转成blod ,上传时使用
 * @param dataurl
 * @returns {Blob}
 */
function dataURLtoBlob(dataUrl) {
	let arr = dataUrl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
}
// 下载成图片
const saveFile = (data, filename) => {
	return new Promise((r) => {
		const aLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
		aLink.href = data;
		aLink.download = filename;
		// 兼容ie
		if (window.navigator.msSaveBlob) {
			try {
				const blobObject = dataURLtoBlob(data);
				window.navigator.msSaveBlob(blobObject, filename);
			} catch (e) {}
		} else {
			const event = document.createEvent('MouseEvents');
			event.initMouseEvent(
				'click',
				true,
				false,
				window,
				0,
				0,
				0,
				0,
				0,
				false,
				false,
				false,
				false,
				0,
				null
			);
			aLink.dispatchEvent(event);
		}

		r(true);
	});
};

// 导出为图片
export const save2Image = ({ dom, fileName }) => {
	return new Promise((r) => {
		const html2canvas = require('html2canvas');

		// 解决html2canvax生成图片只会导出可视区域的问题
		const width = dom.offsetWidth;
		const height = dom.offsetHeight;
		dom.style.width = dom.scrollWidth + 'px';
		dom.style.height = dom.scrollHeight + 'px';
		// 生成图片
		html2canvas(dom, { useCORS: true, dpi: 300 }).then((canvas) => {
			const type = 'png';
			let imgData = canvas.toDataURL(type);
			imgData = imgData.replace(_fixType(type), 'image/octet-stream');
			fileName = fileName.replace(/(.png|.jpg|.jpeg|.gif)$/i, '');
			// 下载
			saveFile(imgData, `${fileName}.${type}`).then((res) => {
				dom.style.width = width + 'px';
				dom.style.height = height + 'px';
				r(true);
			});
		});
	});
};
